<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Login;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Mews\Captcha\Facades\Captcha;

class LoginController extends Controller
{


    public function index(Request $request)
    {
        try {
            $data = $request->all();
            $check = Captcha::check_api($data['captcha'], $data['captchaKey']);
            if (!$check) {
                return $this->returnJson(1, null, '验证码错误或者已过期');
            }
            $credentials = [
                'username' => $data['username'],
                'password' => $data['password'],
            ];
            $token = auth('admin')->attempt($credentials);
            if ($token) {
                $user = auth('admin')->user();
                $login = [
                    'user' => ['nickname' => $user['nickname'], 'avatar' => $user['avatar']],
                    'access_token' => $token,
                    'expires_in' => auth('admin')->factory()->getTTL() * 60
                ];
                return $this->returnJson(0, $login, '登录成功，页面即将跳转...');
            }
            return $this->returnJson(1, null, '账户或者密码错误');
        } catch (\Throwable $e) {
            return $this->returnJson(1, null, $e->getMessage());
        }
    }


}
